package com.cloudcc.mobile.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;

import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.ResultCallBack;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.dao.impl.ContactEngineImpl;
import com.cloudcc.mobile.entity.ChatUser;
import com.cloudcc.mobile.entity.CoworkerEntity;
import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

/**
 * @Description: 联系人管理器
 * @author wangzhiqiang
 * @date 2015-10-15 上午11:43:21
 * 
 */
public class ContactsManager {

	private static ContactsManager instance;
	
	private Context context;
	@Deprecated
	private Map<String, CoworkerEntity> contactList;
	private volatile boolean fromDb = true;
	private volatile boolean hasFilter = true;

	private ContactsManager(Context context) {
		this.context = context;
		this.contactList = new HashMap<String, CoworkerEntity>();
	}

	/**
	 * 获取联系人管理器
	 * 
	 * @return
	 */
	public synchronized static ContactsManager getInstance() {
		if (instance == null) {
			instance = new ContactsManager(AppContext.getInstance());
		}
		return instance;
	}

	/**
	 * 初始化联系人
	 */
	public void init() {
	}

	
	public CoworkerEntity getUserInfoByHXId(String hxUserName){
		String userId = deCodeHXuserName(hxUserName);
		LiteOrm liteOrm = OrmManager.getManager().getOrm();
		QueryBuilder<CoworkerEntity> queryBuilder = new QueryBuilder<CoworkerEntity>(CoworkerEntity.class)
        .where("id like ?", new String[]{userId});
		ArrayList<CoworkerEntity> query = liteOrm.query(queryBuilder);
		return ListUtils.isEmpty(query)?null:query.get(0);
	} 
	
	
	/**
	 * 获取联系人
	 * 
	 * @return
	 */
	public Map<String, CoworkerEntity> getContactList() {
		if (contactList == null || contactList.size() == 0) {
			List<CoworkerEntity> contactes =new ArrayList<CoworkerEntity>();
			contactes = getContactesFromDB();
			contactList = new HashMap<String, CoworkerEntity>();
			if (ListUtils.isEmpty(contactes)) {
				return contactList;
			}
			for (CoworkerEntity sortModel : contactes) {
				contactList.put(sortModel.getHxusername(), sortModel);
			}
			return contactList;
		}
		return contactList;
	}
	/**
	 * 同步联系人 在子线程中进行
	 */
	public void syncContactes() {
		new ContactEngineImpl().getContactsSync(new ResultCallBack<List<CoworkerEntity>>() {
			@Override
			public void onSuccess(List<CoworkerEntity> users) {
				LogUtils.d("imchat", "下载同事列表成功。。");
				saveContactesToDB(users);
			}
			@Override
			public void onFailure(ErrorInfo arg0) {
				LogUtils.d("imchat", "下载同事列表失败。。");
			}
		});
	}
	public ChatUser covert2ChatUser(CoworkerEntity sortModel) {
		ChatUser chatUser = new ChatUser();
		String zero = String.valueOf(0);
		chatUser.setCommentednum(zero);
		chatUser.setPhone(sortModel.getPhone());
		chatUser.setFeedandcomnum(zero);
		chatUser.setPraisenum(zero);
		chatUser.setTitle(sortModel.getTitle());
		chatUser.setEmail(sortModel.getEmail());
		chatUser.setName(sortModel.getName());
		chatUser.setLastModifyDate(zero);
		chatUser.setCreateDate(zero);
		chatUser.setMobile(sortModel.getMobile());
		chatUser.setAddress("");
		chatUser.setAboutme("");
		chatUser.setIsmefollow(sortModel.isIsmefollow());
		chatUser.setIsfollowme(sortModel.isIsfollowme());
		return chatUser;
	}
	
	/** 转换成 ContactEntity 对象类型
	 * @param user
	 * @return
	 */
	public static CoworkerEntity covert2ContactEntity(ChatUser user){
		CoworkerEntity entity = new CoworkerEntity();
		entity.setId(user.getUserid());
		entity.setPhone(user.getPhone());
		entity.setMobile(user.getMobile());
		entity.setEmail(user.getEmail());
		entity.setIsfollowme(user.isIsfollowme());
		entity.setIsmefollow(user.isIsmefollow());
		return entity;
	}




	/**
	 * 从本地数据库 获取 所有缓存的同事数据
	 * 
	 * @return
	 */
	public List<CoworkerEntity> getContactesFromDB() {
		LiteOrm liteOrm = OrmManager.getManager().getOrm();
		List<CoworkerEntity> list = liteOrm.query(CoworkerEntity.class);
		return list;
	}

	/**
	 * 保存联系人信息到数据库
	 * 
	 * @param data
	 */
	public void saveContactesToDB(List<CoworkerEntity> data) {
		if (!ListUtils.isEmpty(data)) {
			LogUtils.d("imchat", "保存同事列表到数据库。。");
			LiteOrm liteOrm = OrmManager.getManager().getOrm();
			liteOrm.save(data);
		}
	}
	
	/** 根据用户id 从数据库读取一个 用户信息
	 * @param userId userid 
	 * @return 不存在  为null
	 */
	public CoworkerEntity getContactById(String userId){
		LiteOrm liteOrm = OrmManager.getManager().getOrm();
		QueryBuilder<CoworkerEntity> whereEquals = new QueryBuilder<CoworkerEntity>(CoworkerEntity.class).whereEquals("id", userId);
		ArrayList<CoworkerEntity> query = liteOrm.query(whereEquals);
		return ListUtils.isEmpty(query)?null:query.get(0);
	}
	public void setFromDB(boolean isNew) {
		fromDb = isNew;
	}
	/**
	 * 生成环信聊天的用户名
	 * 
	 * @param ccuserId
	 *            用户id
	 * @return
	 */
	@SuppressLint("DefaultLocale")
	public String encodeHXuserName(String ccuserId) {
		String hxUserName = (ccuserId + getOrgId()).toLowerCase();
		return hxUserName;
	}

	private String getOrgId(){
		return UserManager.getManager().getUser().orgId;
	}


	/**
	 * 从环信帐号中解密出 cloudcc 的userid （小写）
	 * 
	 * @param hxUserName
	 * @return
	 */
	public String deCodeHXuserName(String hxUserName) {
		if (StringUtils.isBlank(hxUserName)) {
			return "";
		}
		return StringUtils.remove(hxUserName, getOrgId().toLowerCase());
	}
	/**
	 * 清空 缓存的 联系人数据
	 */
	public void clearContactCache(){
		LiteOrm liteOrm = OrmManager.getManager().getOrm();
		liteOrm.delete(CoworkerEntity.class);
	}

	private DisplayImageOptions createDisPlayImageOptions(Drawable defult){
		DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder()
		.showImageOnFail(defult)
		.displayer(new RoundedBitmapDisplayer(100))
		.resetViewBeforeLoading(false)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.delayBeforeLoading(1000)
		.cacheInMemory(true)
		.imageScaleType(ImageScaleType.EXACTLY)// default
		.cacheOnDisc(true)
		.build();
		return displayImageOptions;
	}
	
}
